#include "file.h"

#include <fstream>
#include <iostream>

using namespace File;

// Somewhere between the text file and the shader compiler line breaks get fucked up so we have to set them manually
int AppendLine(char* buffer, std::string s, int pos){
    for(char c:s){
        buffer[pos] = c;
        pos++;
    }
    buffer[pos]='\r';
    buffer[pos+1]='\n';
    pos+=2;
    return pos;
}

char* File::GetTextFileContents(std::string location){
    std::ifstream file;
    std::string line;
    char* buffer;
    unsigned int begin;
    unsigned int end;
    unsigned int length;
    unsigned int pos = 0;

    file.open(location.c_str(), std::ifstream::in);
    if(file.is_open()==false){
        std::cout<<"Failed to open: "<<location<<std::endl;
        return nullptr;
    }
    begin = file.tellg();
    file.seekg(0, std::ios::end);
    end = file.tellg();
    length = end-begin;
    buffer = new char[length+1];    //End of file characters arn't read so we have to add our own
//    std::cout<<"Length of file: "<<length<<std::endl;
    file.seekg(0, std::ios::beg);
    while(std::getline(file, line)){
        pos = AppendLine(buffer, line, pos);
    }
    buffer[length] = '\0';
    file.close();
    return buffer;
}

